package com.ox.head.okex.common.sign;

import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author even
 * @date 2021/2/3 0003 上午 9:27
 * @describe
 * OK-ACCESS-SIGN的请求头是对timestamp + method + requestPath + body字符串(+表示字符串连接)，
 * 以及SecretKey，使用HMAC SHA256方法加密，通过Base64
 */
public class HmacSHA256Base64Utils {
    private final static String UTF8="UTF-8";
    private final static String HMAC_SHA256="HmacSHA256";


    /**
     * 签名
     * @param timestamp
     * @param method
     * @param requestPath
     * @param queryString
     * @param body
     * @param secretKey
     * @return
     * @ahtor even
     * @since
     */
    public static String sign(String timestamp, @NonNull String method, String requestPath,
                              String queryString, String body,@NonNull String secretKey) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        String preHash = preHash(timestamp, method, requestPath, queryString, body);
        byte[] secretKeyBytes = secretKey.getBytes( UTF8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes,HMAC_SHA256);
        Mac hmacSHA256 = Mac.getInstance(HMAC_SHA256);
        hmacSHA256.init(secretKeySpec);
        final String s = Base64.getEncoder().encodeToString(hmacSHA256.doFinal(preHash.getBytes( UTF8)));
        return s;
    }
    /**
     * 字符串拼接方法
     * @param timestamp
     * @param method
     * @param requestPath
     * @param queryString
     * @param body
     * @return
     * @ahtor even
     * @since
     */
    public static String preHash(String timestamp, String method, String requestPath,
                                 String queryString, String body){
        StringBuilder preHash = new StringBuilder();
        preHash.append(timestamp);
        preHash.append(method.toUpperCase());
        preHash.append(requestPath);
        //get方法
        if (StringUtils.hasText(queryString)) {
            //在queryString前面拼接上？
            preHash.append("?").append(queryString);
        }
        //post方法
        if (StringUtils.hasText(body)) {
            preHash.append(body);
        }
        return preHash.toString();
    }
}
